#include "Random.h"
#include <EEPROM.h>
#include "HardwareSerial.h"
#include <MIDI.h>

Random::Random(MIDI *midi) {
  this->midi = midi;
  notemin = 0;
  notemax = 0;
  velocitymin = 0;
  velocitymax = 0;
}

void Random::readFromSerial() {
  if (Serial.available() > 0) {
    notemin = Serial.read();
    delayMicroseconds(4250);
    notemax = Serial.read();
    delayMicroseconds(4250);
    velocitymin = Serial.read();
    delayMicroseconds(4250);
    velocitymax = Serial.read();
    delayMicroseconds(4250);
  }
}

void Random::writeToSerial() {
  Serial.write(notemin);
  Serial.write(notemax);
  Serial.write(velocitymin);
  Serial.write(velocitymax);
}

void Random::readFromMemory(int index) {
  notemin = EEPROM.read(index);
  notemax = EEPROM.read(index + 1);
  velocitymin = EEPROM.read(index + 2);
  velocitymax = EEPROM.read(index + 3);
}

void Random::writeToMemory(int index) {
  EEPROM.write(index, notemin);
  EEPROM.write(index + 1, notemax);
  EEPROM.write(index + 2, velocitymin);
  EEPROM.write(index + 3, velocitymax);
}

void Random::handleNoteOn() {
  if (notec < 6) {
    notes[notec][0] = midi->getStatus();
    notes[notec][1] = midi->getData1();
    notes[notec][2] = midi->getData2();
    notes[notec][3] = random(notemin, notemax);
    notes[notec][4] = random(velocitymin, velocitymax);
    midi->send(notes[notec][0], notes[notec][3], notes[notec][4]);
    notec++;
  }
}

void Random::handleNoteOff() {
  if (notec > 0) { // should always happen!
    for (int i = 0; i < notec; i++) {
      if (notes[i][1] == midi->getData1()) {
        midi->send(midi->getStatus(), notes[i][3], notes[i][4]); // Random velocity?
        if (i < notec - 1) {
          while (i < notec) {
            notes[i][0] = notes[i + 1][0];
            notes[i][1] = notes[i + 1][1];
            notes[i][2] = notes[i + 1][2];
            notes[i][3] = notes[i + 1][3];
            notes[i][4] = notes[i + 1][4];
          }
        }
        notec--;
        break;
      }
    }
  }
}
